package com.yfunc.common.event.executor;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import com.yfunc.common.event.Event;
import com.yfunc.common.event.EventExecutor;
import com.yfunc.common.event.EventHandler;
import com.yfunc.common.event.handlers.AnnotationEventHandler;

public class SimpleEventExecutor implements EventExecutor {

	private Set<EventHandler> handles;

	public SimpleEventExecutor() {
		this.handles =  Collections.synchronizedSet(new HashSet<EventHandler>());
	}

	@Override
	public void publish(Event event) {
		if( event == null) {
			throw new IllegalArgumentException("published null event!");
		}
		this.notifyEvents(event);
	}

	@Override
	public void register(EventHandler handler) {
		if (handler == null) {
			throw new IllegalArgumentException("register null handler!");
		}
		this.handles.add(handler);
	}
	
	@Override
	public void register(Object handler) {
		if (handler == null) {
			throw new IllegalArgumentException("register null handler!");
		}
		
		this.register( new AnnotationEventHandler(handler));
		
	} 
	
	private void notifyEvents(Event event) {
		EventHandler[] eventHanlers = handles.toArray( new EventHandler[0]) ;		
		for (EventHandler handle : eventHanlers) {
			if (handle.isSupported(event)) {
				handle.handle(event);
			}
		}	
	}
}
